package com.android.lovely.ui.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.android.lovely.R
import kotlin.math.max
import kotlin.math.min

/**
 *
 * @author why
 * @date 2025/3/30 20:44
 */
class FontSizeWidget @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 绘制相关的画笔
    private val trackPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val progressPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val thumbPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)

    // 轨道区域
    private val trackRect: RectF = RectF()

    // 进度条参数
    private var min: Float = 0f
    private var max: Float = 100f
    private var value: Float = 0f

    // 视图尺寸
    private var trackHeight: Float = 0f
    private var thumbRadius: Float = 0f
    private var thumbX: Float = 0f

    // 是否正在拖动滑块
    private var isDragging: Boolean = false

    // 值变化监听器
    private var onValueChangeListener: ((Float) -> Unit)? = null

    init {
        // 设置初始样式
        trackPaint.apply {
            color = Color.parseColor("#22FFFFFF")
            style = Paint.Style.FILL
        }

        progressPaint.apply {
            color = Color.parseColor("#6B77FF")
            style = Paint.Style.FILL
        }

        thumbPaint.apply {
            color = Color.parseColor("#6B77FF")
            style = Paint.Style.FILL
        }

        // 从XML中读取自定义属性
        if (attrs != null) {
            val typedArray = context.obtainStyledAttributes(
                attrs,
                R.styleable.CustomSliderView,
                defStyleAttr,
                0
            )

            try {
                min = typedArray.getFloat(R.styleable.CustomSliderView_slider_min_value, min)
                max = typedArray.getFloat(R.styleable.CustomSliderView_slider_max_value, max)
                value = typedArray.getFloat(R.styleable.CustomSliderView_slider_value, value)

                // 确保value在min和max之间
                value = max(min, min(max, value))

                // 颜色属性
                trackPaint.color = typedArray.getColor(
                    R.styleable.CustomSliderView_slider_track_color,
                    trackPaint.color
                )

                progressPaint.color = typedArray.getColor(
                    R.styleable.CustomSliderView_slider_progress_color,
                    progressPaint.color
                )

                thumbPaint.color = typedArray.getColor(
                    R.styleable.CustomSliderView_slider_thumb_color,
                    thumbPaint.color
                )

                // 自定义尺寸值
                val defaultTrackHeight = context.resources.displayMetrics.density * 4
                val defaultThumbRadius = context.resources.displayMetrics.density * 10

                val customTrackHeight = typedArray.getDimension(
                    R.styleable.CustomSliderView_slider_track_height,
                    0f
                )

                val customThumbRadius = typedArray.getDimension(
                    R.styleable.CustomSliderView_slider_thumb_radius,
                    0f
                )

                // 如果在XML中设置了自定义尺寸，则使用这些尺寸
                if (customTrackHeight > 0) {
                    trackHeight = customTrackHeight
                }

                if (customThumbRadius > 0) {
                    thumbRadius = customThumbRadius
                }

            } finally {
                typedArray.recycle()
            }
        }
    }

    /**
     * 设置当前值并刷新视图
     */
    fun setValue(newValue: Float) {
        value = max(min, min(max, newValue))
        updateThumbPosition()
        invalidate()
    }

    /**
     * 获取当前值
     */
    fun getValue(): Float {
        return value
    }

    /**
     * 设置值范围
     */
    fun setRange(minValue: Float, maxValue: Float) {
        min = minValue
        max = maxValue
        value = max(min, min(max, value))
        updateThumbPosition()
        invalidate()
    }

    /**
     * 设置值变化监听器
     */
    fun setOnValueChangeListener(listener: (Float) -> Unit) {
        onValueChangeListener = listener
    }

    /**
     * 根据当前值更新滑块位置
     */
    private fun updateThumbPosition() {
        val availableWidth = width - paddingLeft - paddingRight - 2 * thumbRadius
        val valueRatio = if (max > min) (value - min) / (max - min) else 0f
        thumbX = paddingLeft + thumbRadius + valueRatio * availableWidth
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        // 如果在XML中没有设置自定义尺寸，则根据View的高度计算
        if (trackHeight == 0f) {
            trackHeight = h * 0.2f
        }

        if (thumbRadius == 0f) {
            thumbRadius = h * 0.45f
        }

        // 更新轨道矩形区域
        trackRect.set(
            paddingLeft + thumbRadius,
            (h - trackHeight) / 2,
            w - paddingRight - thumbRadius,
            (h + trackHeight) / 2
        )

        // 初始化滑块位置
        updateThumbPosition()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 绘制背景轨道
        canvas.drawRoundRect(trackRect, trackHeight / 2, trackHeight / 2, trackPaint)

        // 绘制进度条
        val progressRect = RectF(
            trackRect.left,
            trackRect.top,
            thumbX,
            trackRect.bottom
        )
        canvas.drawRoundRect(progressRect, trackHeight / 2, trackHeight / 2, progressPaint)

        // 绘制滑块
        canvas.drawCircle(thumbX, height / 2f, thumbRadius, thumbPaint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                // 检查是否点击在滑块上
                val touchX = event.x
                val touchY = event.y
                val distanceFromThumb = Math.hypot(
                    (touchX - thumbX).toDouble(),
                    (touchY - height / 2f).toDouble()
                )

                // 如果触摸点在滑块附近，开始拖动
                if (distanceFromThumb <= thumbRadius * 1.5) {
                    isDragging = true
                    parent.requestDisallowInterceptTouchEvent(true)
                    updateValueFromPosition(touchX)
                    return true
                }
            }
            MotionEvent.ACTION_MOVE -> {
                if (isDragging) {
                    updateValueFromPosition(event.x)
                    return true
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                if (isDragging) {
                    isDragging = false
                    parent.requestDisallowInterceptTouchEvent(false)
                    return true
                }
            }
        }
        return super.onTouchEvent(event)
    }

    /**
     * 根据触摸位置更新当前值
     */
    private fun updateValueFromPosition(positionX: Float) {
        val availableWidth = width - paddingLeft - paddingRight - 2 * thumbRadius
        val position = positionX.coerceIn(
            paddingLeft + thumbRadius,
            width - paddingRight - thumbRadius
        )

        val ratio = (position - paddingLeft - thumbRadius) / availableWidth
        val newValue = min + ratio * (max - min)

        if (value != newValue) {
            value = newValue
            onValueChangeListener?.invoke(value)
            updateThumbPosition()
            invalidate()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val desiredHeight = context.resources.displayMetrics.density * 48
        val height = resolveSize(desiredHeight.toInt(), heightMeasureSpec)

        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY))
    }
}